//
//  BBQPitSearchViewController.m
//  bbqpitbooking
//
//  Created by Yin Ni Tun on 5/21/11.
//  Copyright 2011 iss. All rights reserved.
//

#import "BBQPitSearchViewController.h"
#import "PitSelectionViewController.h"
#import "PastBooking.h"
#import "ParkDetailView.h"
#import "ParkAreaDetailView.h"
#import "JSONRPCService.h"
#import "Park.h"
#import "ParkArea.h"
#define kDatePickerTag 100

@implementation BBQPitSearchViewController
@synthesize txtDate,txtPark,txtParkArea,webSVC,parkList,bookingDate,parkNames,parkAreaNames,selectedLocation,areaCode,btnPastBooking;
@synthesize btnDate,btnPark,btnParkArea,btnParkMap,btnParkAreaMap,parkView,parkAreaView,parkActionSheet,parkAreaActionSheet;

#define kSearchByCreatorKey @"searchByCreator"
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = @"Search BBQ Pit";
	
	self.parkAreaNames = [[NSMutableArray alloc] init];
	webSVC = [[JSONRPCService alloc] init];
	self.parkList = [webSVC getAllParks];
	
	self.parkNames = [[NSMutableArray alloc] init];
	for(ParkArea *area in self.parkList){
		[self.parkNames addObject:area.park.parkName];	
	}
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[parkdetailview release];
	[parkareadetailview release];
	[parkAreaNames release];
    [super dealloc];
}

- (IBAction) FindPastBooking
{
	PastBooking *pastbooking = [[PastBooking alloc] initWithNibName:@"PastBooking"
															  bundle:nil];
	
	[self.navigationController 
	 pushViewController:pastbooking
	 animated:YES];
	
	[pastbooking release];
	
}

- (IBAction) Search
{
	
	BOOL result = [self checkSelection:txtPark.text andDate:txtDate.text andArea:txtParkArea.text];
	
	if (result) {
		self.selectedLocation = [[ParkArea alloc] init];
		
		for(ParkArea *pa in self.parkList){
			if ([pa.park.parkName isEqualToString:txtPark.text]) { 
				selectedLocation = pa;
				selectedLocation.areaName = txtParkArea.text;
				break;
			}
		}
		
		PitSelectionViewController *pitSelectionViewController = [[PitSelectionViewController alloc]
																  initWithNibName:@"PitSelectionViewController"
																  bundle:nil];
		
		pitSelectionViewController.selectedArea = selectedLocation;
		pitSelectionViewController.bookingDate = txtDate.text;
		
		[self.navigationController 
		 pushViewController:pitSelectionViewController
		 animated:YES];
		
		[selectedLocation release];
		
		[pitSelectionViewController release];
	}else {
		UIAlertView *alertPopUp=[[UIAlertView alloc]
								 initWithTitle:@"BBQ Pit Booking" message:@"Please select required fields" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertPopUp show];
		[alertPopUp release];
	}
}

-(void) dateButtonClick:(id)sender
{
	UIActionSheet *asheet = [[UIActionSheet alloc] initWithTitle:@"Pick the date you want to see." delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Select", nil];
    [asheet showInView:[self.view superview]]; //note: in most cases this would be just self.view, but because I was doing this in a tabBar Application, I use the superview.
    [asheet setFrame:CGRectMake(0, 117, 320, 383)];
    [asheet release];
}

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet1 {
	parkView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 320, 216)];
	
	//Configure picker...
    //[parkView setMinuteInterval:5];
    [parkView setTag: kDatePickerTag];
	
	//Add picker to action sheet
    [actionSheet1 addSubview:parkView];
	
    [parkView release];
	
	//Gets an array af all of the subviews of our actionSheet
    NSArray *subviews = [actionSheet1 subviews];

	//[[subviews objectAtIndex:actionSheet.otherButtonIndex] setFrame:CGRectMake(20, 266, 280, 46)]; 
    [[subviews objectAtIndex:actionSheet1.cancelButtonIndex] setFrame:CGRectMake(20, 317, 280, 46)];
}

- (void)actionSheet:(UIActionSheet *)actionSheet1 clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	if (buttonIndex != [actionSheet1 cancelButtonIndex]) {
			//set Date formatter
			
			NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
			[formatter setDateFormat:@"MM/dd/YYYY h:mm a"];
			
			//Gets our picker
			UIDatePicker *ourDatePicker = (UIDatePicker *) [actionSheet1 viewWithTag:kDatePickerTag];
			
			NSDate *selectedDate = [ourDatePicker date];
			
			NSString *msg = [[NSString alloc] initWithFormat:@"The date that you had selected was, %@", [formatter stringFromDate:selectedDate]];
			[formatter release];
			//UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Date" message:msg delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
			//[alert show];
			//[alert release];
			
			NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
			[dateFormat setDateFormat:@"MMMM dd, YYYY"];
		
			NSString *dateString = [dateFormat stringFromDate:selectedDate];  
			txtDate.text = [NSString stringWithFormat:@"%@",dateString];
			
		[dateFormat release];
		[msg release];
    }
}


//Park Selection
-(void) parkButtonClick:(id)sender
{
	parkActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
	
	parkView = [[UIPickerView alloc] initWithFrame:pickerFrame];
	parkView.showsSelectionIndicator = YES;
	parkView.dataSource = self;
	parkView.delegate = self;
	
	[parkActionSheet addSubview:parkView];
	[parkView release];
	
	UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Select"]];
	closeButton.momentary = YES; 
	closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
	closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
	closeButton.tintColor = [UIColor blackColor];
	[closeButton addTarget:self action:@selector(parkDoneButtonClick:) forControlEvents:UIControlEventValueChanged];
	[parkActionSheet addSubview:closeButton];
	[closeButton release];
	
	[parkActionSheet showInView:self.view];
	[parkActionSheet setBounds:CGRectMake(0, 0, 320, 485)];	
}


-(void) parkDoneButtonClick:(id)sender
{
	[parkActionSheet dismissWithClickedButtonIndex:0 animated:YES];
	
	for(ParkArea *pa in self.parkList){
		if ([pa.park.parkName isEqualToString:txtPark.text]) { 
			self.areaCode = pa.park.postalCode;
			break;
		}
	}
	
	self.parkAreaNames = [webSVC getAllParkAreas:txtPark.text];
	[parkActionSheet release];
}

//Park Area Selection
-(void) parkAreaButtonClick:(id)sender
{
	if ([self.parkAreaNames count] == 0) {
		return;
	}
	parkAreaActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
	
	parkAreaView = [[UIPickerView alloc] initWithFrame:pickerFrame];
	parkAreaView.showsSelectionIndicator = YES;
	parkAreaView.dataSource = self;
	parkAreaView.delegate = self;
	
	[parkAreaActionSheet addSubview:parkAreaView];
	[parkAreaView release];
	
	UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Select"]];
	closeButton.momentary = YES; 
	closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
	closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
	closeButton.tintColor = [UIColor blackColor];
	[closeButton addTarget:self action:@selector(parkAreaDoneButtonClick:) forControlEvents:UIControlEventValueChanged];
	[parkAreaActionSheet addSubview:closeButton];
	[closeButton release];
	
	[parkAreaActionSheet showInView:self.view];
	[parkAreaActionSheet setBounds:CGRectMake(0, 0, 320, 485)];	
}


-(void) parkAreaDoneButtonClick:(id)sender
{
	[parkAreaActionSheet dismissWithClickedButtonIndex:0 animated:YES];
	[parkAreaActionSheet release];
}


#pragma mark -
#pragma mark Picker Delegate Methods
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
	
	if(pickerView == parkView) {
		return [self.parkNames objectAtIndex:row];   
		
    } else 
	{    
		return [self.parkAreaNames objectAtIndex:row];   
    }
}


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
	return 1; 
	
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
	if(pickerView == parkView) {
		return [self.parkNames count];
		    
    } else{    
		return [self.parkAreaNames count];
    } 
}

-(void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	if(pickerView == parkView) {
		NSString *selectedPark = [self.parkNames objectAtIndex:row];
		txtPark.text = selectedPark;
	}else {
		NSString *selectedArea = [self.parkAreaNames objectAtIndex:row];
		txtParkArea.text = selectedArea;
	}
}


-(void) parkMapButtonClick:(id)sender
{
	parkdetailview = [[ParkDetailView alloc] init];
	parkdetailview.postalCode = self.areaCode;
	[[self navigationController] pushViewController:parkdetailview 
										   animated:YES]; 
}

-(void) parkAreaMapButtonClick:(id)sender
{
	parkareadetailview = [[ParkAreaDetailView alloc] init];
	//NSLog(@"PostalCode : %@",self.selectedLocation.park.postalCode);
	parkareadetailview.postalCode = self.areaCode;
	[[self navigationController] pushViewController:parkareadetailview 
										   animated:YES]; 
}

-(BOOL) checkSelection:(NSString *) ParkText andDate:(NSString *) DateText andArea:(NSString *) AreaText{
	
	if ([ParkText length] == 0) {
		return FALSE;
	}else if ([DateText length] == 0) {
		return FALSE;
	}else if ([AreaText length] == 0) {
		return FALSE;
	}else {
		return TRUE;
	}
}


@end
